#include "mainwid.h"
#include "ui_mainwid.h"


Mainwid::Mainwid(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Mainwid)
{
    ui->setupUi(this);
    qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "7777");



    table =new QTableWidget;
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setEditTriggers(QAbstractItemView::CurrentChanged);
    table->setColumnCount(7);
    table->setHorizontalHeaderLabels(QStringList()<<"名称"<<"所在地"<<"温度"<<"湿度"<<"状态"<<"空调温度"<<"详情");

    ui->tablewidget->setColumnCount(1);
    ui->tablewidget->setHorizontalHeaderLabels(QStringList()<<"基站列表");
    ui->tablewidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tablewidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    baojing = new jing;
    connect(ui->add,&QPushButton::clicked,this,&Mainwid::addbasic);
    connect(ui->jing_diary,&QPushButton::clicked,this,&Mainwid::jingbasic);
    connect(ui->del,&QPushButton::clicked,this,&Mainwid::deletebasic);
    connect(ui->update,&QPushButton::clicked,this,&Mainwid::flushtable);
    connect(ui->xiangxi,&QPushButton::clicked,this,&Mainwid::showxiangxi);

    connect(table,&QTableWidget::cellChanged,this,&Mainwid::Tablechange);

    connect(ui->tablewidget, &QTableWidget::cellDoubleClicked, this, &Mainwid::doubleclickplay);

    client = new QMQTT::Client(QHostAddress("127.0.0.1"),1883);
    client->setClientId("mqttx_05674e11");
    client->setUsername("1231");
    client->setPassword("123");
    on_pb_connect_clicked();
    connect(client,SIGNAL(received(QMQTT::Message)),this,SLOT(doDataReceived(QMQTT::Message)));



    _myChannel = new myChannel(this);
    _mItemModel =new QStandardItemModel(this);

    QWebChannel* web_channel = new QWebChannel(this);
    web_channel->registerObject("qtChannel",_myChannel);
    ui->webengineview->page()->setWebChannel(web_channel);
    ui->webengineview->load(QUrl("qrc:/smap/mainwid.html"));

    QObject::connect(ui->pushButton_setcity, &QPushButton::clicked, this, &Mainwid::setCity);
//    QObject::connect(_myChannel, &myChannel::setCityLable, [this](QString city) {
//    });
    QObject::connect(_myChannel,&myChannel::sendAutocomplete,this,&Mainwid::setAutoComplete);
}


void Mainwid::showxiangxi(){
    int now = 0;
    while(now < table->rowCount())
    {
        if(table->item(now,0)->text() == ui->name->text()){
            openchild(now);
            break;
        }
        now++;
    }
}

void Mainwid::doubleclickplay(int a,int b)
{
    qDebug()<<"woyunxingle";
    ui->name->setText(table->item(a,0)->text());
    ui->address->setText(table->item(a,1)->text());
    ui->nei_wd->setText(table->item(a,2)->text());
    ui->shidu->setText(table->item(a,3)->text());
    ui->kongtiao->setText(table->item(a,4)->text());
}

Mainwid::~Mainwid()
{
    delete ui;
}


void Mainwid::setCity()
{
    QString city = ui->lineEdit_setcity->text().trimmed();
    if (city.size() == 0)
    {
        QMessageBox::warning(this,"Warning","please enter a address!");
        return;
    }
    int now =0;
    while(now < table->rowCount()){
        if(city == table->item(now,0)->text()){
            city = table->item(now,1)->text();
            doubleclickplay(now,0);
            break;
        }
    }
    _myChannel->setCity(city);
}

void Mainwid::setCity_addr(QString addr)
{
    if (addr.size() == 0)
    {
        QMessageBox::warning(this,"Warning","please enter a address!");
        return;
    }
    _myChannel->setCity(addr);
}

void Mainwid::setAutoComplete(QJsonObject result)
{
    std::cout<<"in setAuto"<<std::endl;
    _mItemModel->clear();
    if(!(result.contains("tips")&&result["tips"].isArray()))
    {
        return;
    }

    for(auto e:result["tips"].toArray())
    {
        QJsonObject d=e.toObject();
        if(d.contains("name"))
        {
            QString s=d["name"].toString();
            if(s.size()>0)
            {
                QStandardItem * item=new QStandardItem(s);
                _mItemModel->appendRow(item);
                std::cout<<s.toStdString()<<std::endl;
            }
        }
    }

}




void Mainwid::addmess()
{
    disconnect(table,&QTableWidget::cellChanged,0,0);
    QString name=addjizhan->getname(),address=addjizhan->getaddress();
    xx.push_back(NULL);
    xx[++count] = new QPushButton("详情");
    int irow =table->rowCount();
    table->setRowCount(irow+1);
    table->setItem(irow,0,new QTableWidgetItem(name));
    table->setItem(irow,1,new QTableWidgetItem(address));
    table->setItem(irow,2,new QTableWidgetItem(0));
    table->setItem(irow,3,new QTableWidgetItem(0));
    table->setItem(irow,4,new QTableWidgetItem(0));
    table->setItem(irow,5,new QTableWidgetItem(0));
    table->setCellWidget(irow,6,xx[count]);
    ui->tablewidget->setRowCount(irow+1);
    ui->tablewidget->setItem(irow,0,new QTableWidgetItem(name));
    for(int i=0;i<5;i++)
    {
        item = table->item(irow,i);
        item->setFlags(Qt::ItemIsEnabled);//设置改item不可修改；
    }
    client->subscribe(name.trimmed());
    chi[name] = new child;
//    connect(xx[count],&QPushButton::clicked,this,&Mainwid::openchild);
    connect(table,&QTableWidget::cellChanged,this,&Mainwid::Tablechange);

}

void Mainwid::addbasic()
{
    addjizhan = new Add;
    addjizhan->show();
    QObject::connect(addjizhan,&Add::closeBox,this,&Mainwid::addmess);

}

void Mainwid::jingbasic()
{
    baojing->show();
}

void Mainwid::openchild(int i)
{

    chi[table->item(i,0)->text()]->show();
}


void Mainwid::deletebasic()
{

    int rowIndex = ui->tablewidget->currentRow();
    if (rowIndex != -1)
     {
        QList<QTableWidgetItem*>items =table->selectedItems();
        QMessageBox::StandardButton result=QMessageBox::question(this,"删除","确定要删除该基站吗？");
        if(result == QMessageBox::Yes)
        {

            QString name,addr;
            QFile file("basic.txt");
            file.open(QIODevice::ReadOnly);
            QDataStream read(&file);
            QFile file1("1.txt");
            file1.open(QIODevice::WriteOnly);
            QDataStream write(&file1);
           while(!read.atEnd())
           {
               read >> name >> addr;
               if(name!=table->item(rowIndex,0)->text()) write<<name<<addr;

               else client->unsubscribe(name);
           }
           file.close();
           file1.close();
           file.remove();
           file1.rename("basic.txt");
           table->removeRow(rowIndex);
        }
    }

    _myChannel->delc();
    flushtable();
}


void Mainwid::flushtable()
{

    disconnect(table,&QTableWidget::cellChanged,0,0);
    QFile file("basic.txt");
    file.open(QIODevice::ReadOnly);
    QDataStream  datastr(&file);
    QString name,addr;
    table->setRowCount(0);
    ui->tablewidget->setRowCount(0);
    while(!datastr.atEnd())
    {
        xx.push_back(NULL);
        xx[++count] =new QPushButton("详情");
        table->setRowCount(table->rowCount()+1);
        ui->tablewidget->setRowCount(ui->tablewidget->rowCount()+1);
        datastr>>name>>addr;
        ui->tablewidget->setItem(ui->tablewidget->rowCount()-1,0,new QTableWidgetItem(name));
        table->setItem(table->rowCount()-1,0,new QTableWidgetItem(name));
        table->setItem(table->rowCount()-1,1,new QTableWidgetItem(addr));
        table->setItem(table->rowCount()-1,2,new QTableWidgetItem(0));
        table->setItem(table->rowCount()-1,3,new QTableWidgetItem(0));
        table->setItem(table->rowCount()-1,4,new QTableWidgetItem(0));
        table->setItem(table->rowCount()-1,5,new QTableWidgetItem(0));//通过直接从文件读写的方式来更新表格信息
        table->setCellWidget(table->rowCount()-1,6,xx[count]);
        Mainwid::setCity_addr(addr);
        table->item(table->rowCount()-1,0)->setFlags(Qt::ItemIsEnabled);//设置改item不可修改；
        for(int i=0;i<5;i++)
        {
            item = table->item(table->rowCount()-1,i);
            item->setFlags(Qt::ItemIsEnabled);//设置改item不可修改；
        }
        client->subscribe(name.trimmed());
        client->subscribe(name.trimmed() + "_2");
        client->subscribe(name.trimmed() + "_shi");
        chi[name] = new child;qDebug()<<"yunxing";
        connect(xx[count],&QPushButton::clicked,this,&Mainwid::openchild);
    }
    connect(table,&QTableWidget::cellChanged,this,&Mainwid::Tablechange);
}

void Mainwid::on_pb_connect_clicked()
{

    if(!client->isConnectedToHost())
    {
        client->connectToHost();
        qDebug()<<"已连接";
    }
    else {
        client->disconnectFromHost();
        qDebug()<<"未连接";
    }
}

QString Mainwid::get_last_wen(QString name)
{
    return jizhan[name].last();
}

void Mainwid::doDataReceived(QMQTT::Message message)
{
    if(message.topic().length() > 2 && message.topic().right(2) == "_2"){
        chi[message.topic().left(message.topic().length()-2)]->setvalue2(message.payload());
        return ;
    }//提交数据为室外温度,否则为室内温度

    if(message.topic().length() > 4 && message.topic().right(4) == "_shi"){
        chi[message.topic().left(message.topic().length()-4)]->setvalue3(message.payload());
        ui->shidu->setText(message.payload());

        return ;
    }

    qDebug() << message.topic().left(message.topic().length());

    QString str;
    if(message.payload().toInt() < 0) str = message.payload().mid(1);
    else {
        str = message.payload();
    }
    jizhan[message.topic()].enqueue(str);
    if(jizhan[message.topic()].size()>50) jizhan[message.topic()].dequeue();
    chi[message.topic()]->setvalue(str);
    int now =0;

    if(message.topic() == ui->name->text()){
        ui->nei_wd->setText(str);
    }
    while(now < table->rowCount() )
    {
        if(table->item(now,0)->text()==message.topic())
        {
            table->setItem(now,2,new QTableWidgetItem(jizhan[message.topic()].last()));
            item = table->item(now,2);
            item->setFlags(Qt::ItemIsEnabled);
            int mess = message.payload().toInt();
            if(mess>35 || mess < 0)
            {
                QString level,leixing;
                if(mess<0) {
                    mess = -mess;
                    level = "高";
                    leixing = "停电";
                }
                else level = "低",leixing = "温度过高";
                baojing->getdata(table->item(now,0)->text(),table->item(now,1)->text(),table->item(now,2)->text(),"75%",level,leixing);
            }
            break;
        }
        now++;
    }
}


void Mainwid::Tablechange(int row)
{
    QString topic,payload;
    topic = table->item(row,0)->text();
    payload = ui->kongtiao->text();
    topic += "push";
    qDebug() << topic ;
    QMQTT::Message message(136,topic,payload.toUtf8());

    client->publish(message);
}



void Mainwid::on_kongtiao_textChanged(const QString &arg1)
{
    int now =0;

    while(now < table->rowCount() )
    {
        if(ui->name->text() == table->item(now,0)->text()) {
            table->item(now,4)->setText(arg1);
            break;
        }
        now++;
    }
}
